<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-top-panel :span="24">
        <el-form inline label-width="120px" :model="queryForm" @submit.prevent>
          <el-form-item label="用户名">
            <el-input
              v-model.trim="queryForm.username"
              clearable
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              v-model.trim="queryForm.telphone"
              clearable
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item label="上级部门" prop="">
            <treeselect
              v-model="queryForm.orgid"
              class="query"
              :multiple="true"
              :limit="3"
              :limit-text="count"
              :load-options="loadOptions"
              no-children-text="空"
              no-options-text="加载中"
              no-results-text="无"
              :normalizer="hasIdNoLabelHasName"
              placeholder="上级部门"
              :show-count="true"
              :options="treePartData"
              :searchable="true"
            />
          </el-form-item>
          <el-form-item label="角色组" prop="">
            <treeselect
              v-model="queryForm.groupid"
              class="query"
              :multiple="true"
              :limit="3"
              :limit-text="count"
              :load-options="loadOptions"
              no-children-text="空"
              no-options-text="加载中"
              no-results-text="无"
              :normalizer="hasIdNoLabelHasName"
              placeholder="角色组"
              :show-count="true"
              :options="treeRoleData"
              :searchable="true"
            />
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :span="24">
        <el-button :icon="Plus" type="primary" @click="handleEdit($event)">
          添加
        </el-button>
        <el-button :icon="Search" type="primary" @click="queryData">
          查询
        </el-button>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column align="center" label="序号" width="55">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="id"
        prop="id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="用户名"
        prop="username"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="手机号"
        prop="telphone"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="部门"
        prop="orgname"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span v-for="item in row.org" :key="item.id">
            {{ item.orgname }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="角色组"
        prop="groupname"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span v-for="item in row.group" :key="item.id">
            {{ item.groupname }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="200"
      >
        <template #default="{ row }">
          <el-button text type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button text type="primary" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { doDelete, getList } from '@/api/userManagement'
  import { getList as getPartList } from '@/api/departmentManagement'
  import { getList as getRoleList } from '@/api/roleManagement'
  import Treeselect from 'vue3-treeselect'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'UserManagement',
    components: {
      Edit: defineAsyncComponent(() =>
        import('@/views/components/UserManagementEdit')
      ),
      Treeselect,
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        editRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        treePartData: [],
        treeRoleData: [],
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          username: '',
        },
        hasIdNoLabelHasName(node) {
          return {
            label: node.name,
            children:
              node.children && node.children.length > 0 ? node.children : 0,
          }
        },
      })

      const fetchPartData = async () => {
        state.listLoading = true
        const {
          data: { list },
        } = await getPartList(state.queryForm)
        state.treePartData = list
      }

      const fetchRoleData = async () => {
        state.listLoading = true
        const {
          data: { list },
        } = await getRoleList(state.queryForm)
        state.treeRoleData = list
      }

      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleEdit = (row) => {
        if (row.id) {
          state['editRef'].showEdit(row)
        } else {
          state['editRef'].showEdit()
        }
      }
      const handleDelete = (row) => {
        if (row.id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ id: row.id })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.id).join()
            $baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ id: ids })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { list, totalCount },
        } = await getList(state.queryForm)
        console.log()
        state.list = list
        state.total = totalCount
        state.listLoading = false
      }
      onMounted(() => {
        fetchData()
        fetchPartData()
        fetchRoleData()
      })

      return {
        ...toRefs(state),
        setSelectRows,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        fetchPartData,
        fetchRoleData,
        Delete,
        Plus,
        Search,
      }
    },
  })
</script>
<style lang="scss" scoped>
  :deep() {
    .vue-treeselect__control {
      border-radius: 2px;
    }
    .el-form-item__content {
      line-height: normal;
    }
    .tree-select,
    .query.vue-treeselect {
      width: 220px;
      &__multi-value-label {
        // width: 85%;
        display: block;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: normal;
      }
      .vue-treeselect__multi-value-item-container {
        padding-top: 2px;
      }
      &--has-value,
      &__multi-value {
        display: flex;
        margin-bottom: 0;
      }
      &__limit-tip-text {
        min-width: 40px;
      }
      &__x-container {
        position: absolute;
        z-index: 100;
        top: 13px;
        right: 20px;
      }

      &__menu {
        // width: max-content !important;
        width: 100%;
        // max-width: 20em;
      }
      &__control {
        height: 32px;
      }
      &__placeholder,
      &__single-value {
        line-height: 32px;
      }
    }
  }
</style>
